package site.isscloud.jt809;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class VehicleLocationMessage {

    private String vehicleNo;
    private byte vehicleColor;
    private GPSData gpsData;
    private long alarmFlag;
    private long statusFlag;

    public VehicleLocationMessage(String vehicleNo, byte vehicleColor, GPSData gpsData, long alarmFlag, long statusFlag) {
        this.vehicleNo = vehicleNo;
        this.vehicleColor = vehicleColor;
        this.gpsData = gpsData;
        this.alarmFlag = alarmFlag;
        this.statusFlag = statusFlag;
    }

    public byte[] toByteArray() {
        ByteBuffer buffer = ByteBuffer.allocate(21 + 1 + 28 + 4 + 4)
                .order(ByteOrder.BIG_ENDIAN);

        // 写入车牌号
        byte[] vehicleNoBytes = new byte[21];
        byte[] srcVehicleNo = vehicleNo.getBytes();
        System.arraycopy(srcVehicleNo, 0, vehicleNoBytes, 0, Math.min(srcVehicleNo.length, 21));
        buffer.put(vehicleNoBytes);

        // 写入车牌颜色
        buffer.put(vehicleColor);

        // 写入GPS数据
        buffer.put(gpsData.toByteArray());

        // 写入报警标志
        buffer.putInt((int) alarmFlag);

        // 写入车辆状态
        buffer.putInt((int) statusFlag);

        return buffer.array();
    }

    public static VehicleLocationMessage fromByteArray(byte[] bytes) {
        ByteBuffer buffer = ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN);
        
        // 读取车牌号
        byte[] vehicleNoBytes = new byte[21];
        buffer.get(vehicleNoBytes);
        String vehicleNo = new String(vehicleNoBytes).trim();
        
        // 读取车牌颜色
        byte vehicleColor = buffer.get();
        
        // 读取GPS数据
        byte[] gpsDataBytes = new byte[28];
        buffer.get(gpsDataBytes);
        GPSData gpsData = GPSData.fromByteArray(gpsDataBytes);
        
        // 读取报警标志
        long alarmFlag = buffer.getInt() & 0xFFFFFFFFL;
        
        // 读取车辆状态
        long statusFlag = buffer.getInt() & 0xFFFFFFFFL;
        
        return new VehicleLocationMessage(vehicleNo, vehicleColor, gpsData, alarmFlag, statusFlag);
    }

    @Override
    public String toString() {
        return String.format("VehicleLocationMessage{vehicleNo='%s', vehicleColor=%d, gpsData=%s, alarmFlag=%d, statusFlag=%d}",
                vehicleNo, vehicleColor, gpsData, alarmFlag, statusFlag);
    }
}